//
//  RCOrderUpdateStateVC.m
//  RocketProject
//
//  Created by chen jiedan on 13-10-3.
//  Copyright (c) 2013年 Rocket. All rights reserved.
//

#import "RCOrderUpdateStateVC.h"
#import "CommonDefines.h"
#import "UIColor-Expanded.h"
#import "IManager+RequestServerDetailInfo.h"
#import "AppDelegate.h"
#import "RCOrderManagerVC.h"

#define kTextBGImageFile             @"image_about_textBG.png"

@interface RCOrderUpdateStateVC ()<IManagerDelegate,UIActionSheetDelegate,UITextFieldDelegate,UITextViewDelegate>{
    UIButton *statusBtn;
    UILabel *_statusLabel;
    UITextField *priceLabel;
    UITextView *inputField;
    UILabel *_resumeTypeLabel;
    
    int64_t _reqID;
    
    BOOL _isRealOrder;
}


@property (nonatomic, copy) NSString *uniqueID;
@property (nonatomic, copy) NSString *eventID;

@property (nonatomic, copy) NSString *price;
@property (nonatomic, assign) RCListReviewStatus  status;
@property (nonatomic, copy) NSString *notes;

@end

@implementation RCOrderUpdateStateVC
@synthesize uniqueID = _uniqueID;
@synthesize eventID = _eventID;
@synthesize price = _price;
@synthesize status = _status;
@synthesize notes = _notes;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}


- (id) initWithUniqueID:(NSString *)orderID
            withEventID:(NSString *)eventID
            withIsOrder:(BOOL)isRealOrder
              withState:(RCListReviewStatus)status
              withPrice:(NSString *)price
               withNote:(NSString *)notes
{
    self = [super init];
    if (self) {
        self.eventID = eventID;
        self.uniqueID = orderID;
        self.price = price;
        self.status  = status;
        self.notes = notes;
        _isRealOrder = isRealOrder;
        [self initKeyBoard];
    }
    return self;
}

-(void)initKeyBoard{
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}



- (void) dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    [[IManager sharedInstance] cancelFetchDataRequestByRequestID:_reqID];
    KF_RELEASE_SAFELY(_uniqueID);
    KF_RELEASE_SAFELY(_price);
    KF_RELEASE_SAFELY(_eventID);
    KF_RELEASE_SAFELY(_notes);
    [super dealloc];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    self.titleLabelText = @"更新订单状态";
    self.navigationItem.titleView = [self createTitleView];
    
    UILabel *stateLabel = [[UILabel alloc] initWithFrame:CGRectMake(14, 17, 70, 14)];
    stateLabel.backgroundColor = [UIColor clearColor];
    stateLabel.textColor = [UIColor colorWithHex:0xff7b7b7b];
    stateLabel.text = @"当前状态：";
    stateLabel.font = [UIFont fontWithName:kFontNameLightHeiti size:14];
    [self.viewContainer addSubview:stateLabel];
    [stateLabel release];
    
    NSString *resourcePath = [[NSBundle mainBundle]resourcePath];
    NSString *textBGFilePath = [resourcePath stringByAppendingPathComponent:kTextBGImageFile];
    UIImage *textBGImage = [UIImage imageWithContentsOfFile:textBGFilePath];
    textBGImage = [textBGImage resizableImageWithCapInsets:UIEdgeInsetsMake(5, 5, 5, 5)];
    
    statusBtn = [[UIButton alloc] initWithFrame:CGRectMake(80, 14, 96, 20)];
    statusBtn.backgroundColor = [UIColor clearColor];
    [statusBtn setBackgroundImage:textBGImage forState:UIControlStateNormal];
    [statusBtn setBackgroundImage:textBGImage forState:UIControlStateHighlighted];
    
    
    _statusLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 3, 86, 14)];
    _statusLabel.backgroundColor = [UIColor clearColor];
    _statusLabel.textColor = [UIColor colorWithHex:0xff979797];
    _statusLabel.font = [UIFont fontWithName:kFontNameLightHeiti size:14];
    _statusLabel.textAlignment = UITextAlignmentLeft;
    
    if (self.status == RCListReviewStatus_UnderReview) {
        
        _statusLabel.text = @"待审核";
    }else if (self.status == RCListReviewStatus_ReviewSuccess){
        
        _statusLabel.text = @"审核通过";
    }else if (self.status == RCListReviewStatus_ReviewFailed){
        
        _statusLabel.text = @"审核失败";
    }
    [statusBtn addSubview:_statusLabel];
    [_statusLabel release];
    
    
    [statusBtn addTarget:self action:@selector(changeState) forControlEvents:UIControlEventTouchUpInside];
    
    [self.viewContainer addSubview:statusBtn];
    [statusBtn release];
    
    if (_isRealOrder) {
        
        UILabel *resumeWord = [[UILabel alloc] initWithFrame:CGRectMake(14, 46, 70, 15)];
        resumeWord.backgroundColor = [UIColor clearColor];
        resumeWord.textColor = [UIColor colorWithHex:0xff7b7b7b];
        resumeWord.text = @"消费方式：";
        resumeWord.font = [UIFont fontWithName:kFontNameHelvetica size:14];
        [self.viewContainer addSubview:resumeWord];
        [resumeWord release];
        
        UIButton *resumeTypeButton = [[UIButton alloc] initWithFrame:CGRectMake(80, 43, 96, 20)];
        resumeTypeButton.backgroundColor = [UIColor clearColor];
        [resumeTypeButton setBackgroundImage:textBGImage forState:UIControlStateNormal];
        [resumeTypeButton setBackgroundImage:textBGImage forState:UIControlStateHighlighted];
        
        
        _resumeTypeLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 3, 86, 14)];
        _resumeTypeLabel.backgroundColor = [UIColor clearColor];
        _resumeTypeLabel.textColor = [UIColor colorWithHex:0xff979797];
        _resumeTypeLabel.font = [UIFont fontWithName:kFontNameLightHeiti size:14];
        _resumeTypeLabel.textAlignment = UITextAlignmentLeft;
        _resumeTypeLabel.text = @"现金";
        
        [resumeTypeButton addSubview:_resumeTypeLabel];
        [_resumeTypeLabel release];
        
        
        [resumeTypeButton addTarget:self action:@selector(changeResumeType) forControlEvents:UIControlEventTouchUpInside];
        
        [self.viewContainer addSubview:resumeTypeButton];
        [resumeTypeButton release];
        
        
        
        UILabel *price = [[UILabel alloc] initWithFrame:CGRectMake(14, 75, 70, 15)];
        price.backgroundColor = [UIColor clearColor];
        price.textColor = [UIColor colorWithHex:0xff7b7b7b];
        price.text = @"消费金额：";
        price.font = [UIFont fontWithName:kFontNameHelvetica size:14];
        [self.viewContainer addSubview:price];
        [price release];
        
        UIImageView *accountTextImageView = [[UIImageView alloc]initWithFrame:CGRectMake(80, 72, 96, 20)];
        accountTextImageView.backgroundColor = [UIColor clearColor];
        [accountTextImageView setImage:textBGImage];
        accountTextImageView.userInteractionEnabled = YES;
        
        priceLabel = [[UITextField alloc] initWithFrame:CGRectMake(10, 0, 86, 20)];
        priceLabel.borderStyle = UITextBorderStyleNone;
        priceLabel.delegate = self;
        priceLabel.textColor = [UIColor colorWithHex:0xff979797];
        priceLabel.font = [UIFont fontWithName:kFontNameHelvetica size:14];
        priceLabel.textAlignment = UITextAlignmentLeft;
        priceLabel.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        priceLabel.clearButtonMode = UITextFieldViewModeWhileEditing;
        priceLabel.autocorrectionType = UITextAutocorrectionTypeNo;
        priceLabel.autocapitalizationType = UITextAutocapitalizationTypeNone;
        priceLabel.returnKeyType = UIReturnKeyDone;
        priceLabel.text = self.price;
        
        [accountTextImageView addSubview:priceLabel];
        [priceLabel release];
        
        [self.viewContainer addSubview:accountTextImageView];
        [accountTextImageView release];
    }
   
    
    
    UILabel *msgLabel = [[UILabel alloc] initWithFrame:CGRectMake(14, 101, 70, 14)];
    msgLabel.backgroundColor = [UIColor clearColor];
    msgLabel.textColor = [UIColor colorWithHex:0xff7b7b7b];
    msgLabel.font = [UIFont fontWithName:kFontNameLightHeiti size:14];
    msgLabel.text = @"备注：";
    [self.viewContainer addSubview:msgLabel];
    [msgLabel release];
    
    
    UIImageView *inputTextImageView = [[UIImageView alloc]initWithFrame:CGRectMake(80, 101, 226, 160)];
    inputTextImageView.backgroundColor = [UIColor clearColor];
    [inputTextImageView setImage:textBGImage];
    inputTextImageView.userInteractionEnabled = YES;
    
    inputField = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, 226, 160)];
    inputField.backgroundColor = [UIColor clearColor];
    inputField.delegate = self;
    inputField.textColor = [UIColor colorWithHex:0xff979797];
    inputField.font = [UIFont fontWithName:kFontNameLightHeiti size:12];
    [inputField setReturnKeyType:UIReturnKeyDone];
    [inputTextImageView addSubview:inputField];
    inputField.text = self.notes;
    [inputField release];
    
    [self.viewContainer addSubview:inputTextImageView];
    [inputTextImageView release];
    
    
    UIButton  *submitBtn = [[UIButton alloc] initWithFrame:CGRectMake(14, 274, 320-28, 40)];
    [submitBtn setTitle:@"提交" forState:UIControlStateNormal];
    [self.viewContainer addSubview:submitBtn];
    UIImage *loginIMG = [UIImage imageNamed:@"login_btn"];
    [submitBtn setBackgroundImage:loginIMG forState:UIControlStateNormal];
    [submitBtn addTarget:self action:@selector(submitPress) forControlEvents:UIControlEventTouchUpInside];
    [submitBtn release];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void) changeState
{
    NSString *actionSheetTitle = @"设置状态"; //Action Sheet Title
    NSString *other1 = @"待审核";
    NSString *other2 = @"审核通过";
    NSString *other3 = @"审核失败";
    NSString *cancelTitle = @"取消";
    UIActionSheet *actionSheet = [[UIActionSheet alloc]
                                  initWithTitle:actionSheetTitle
                                  delegate:self
                                  cancelButtonTitle:cancelTitle
                                  destructiveButtonTitle:nil
                                  otherButtonTitles:other1, other2, other3, nil];
    actionSheet.tag = 101;
    [actionSheet showInView:self.view];
}

-(void)changeResumeType{
    UIActionSheet *actionSheet = [[UIActionSheet alloc]
                                  initWithTitle:@"消费方式"
                                  delegate:self
                                  cancelButtonTitle:@"取消"
                                  destructiveButtonTitle:nil
                                  otherButtonTitles:@"现金", @"会员卡", nil];
    actionSheet.tag = 102;
    [actionSheet showInView:self.view];
}


- (void) actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    //Get the name of the current pressed button
    NSString *buttonTitle = [actionSheet buttonTitleAtIndex:buttonIndex];
    if (actionSheet.tag == 101) {
        if  ([buttonTitle isEqualToString:@"待审核"]) {
            _statusLabel.text =  @"待审核";
            self.status = RCListReviewStatus_UnderReview;
        }else if ([buttonTitle isEqualToString:@"审核通过"]) {
            
            _statusLabel.text =  @"审核通过";
            self.status = RCListReviewStatus_ReviewSuccess;
        }else if ([buttonTitle isEqualToString:@"审核失败"]) {
            self.status = RCListReviewStatus_ReviewFailed;
            
            _statusLabel.text =  @"审核失败";
        }
    }else{
        if  ([buttonTitle isEqualToString:@"现金"]) {
            _resumeTypeLabel.text =  @"现金";
            
        }else if ([buttonTitle isEqualToString:@"会员卡"]) {
            
            _resumeTypeLabel.text =  @"会员卡";

        }
    }
    
   
}
- (void) submitPress
{
    [[IManager sharedInstance] cancelFetchDataRequestByRequestID:_reqID];
    
    NSString *chargeType = @"1";
    if ([_resumeTypeLabel.text isEqualToString:@"现金"]) {
        chargeType = @"1";
    }else{
        chargeType = @"2";
    }
    
    _reqID = [[IManager sharedInstance] requestPostOrderInfo:self.uniqueID withEventID:self.eventID withIsOrder:_isRealOrder withStatus:self.status withChargeType:chargeType withPrice:priceLabel.text withContent:inputField.text withDelegate:self];
    
//    _reqID = [[IManager sharedInstance] requestPostOrderInfo:self.uniqueID withIsOrder:_isRealOrder withStatus:self.status withPrice:priceLabel.text withContent:inputField.text withDelegate:self];
//   _reqID = [[IManager sharedInstance] requestPostOrderInfo:self.uniqueID withStatus:self.status withPrice:priceLabel.text withContent:inputField.text withDelegate:self];
}



- (void) updateViewForError:(NSError *)errorInfo withRequestId:(int64_t)requestId
{
    [RCAppDelegate alertWithCustomizeString:@"提交失败"];
}

- (void) updateViewForSuccess:(IDataModel *)dataModel withRequestId:(int64_t)requestId
{
    if (dataModel.errorNO == RCErrorTypeNoError) {
        NSArray *t = [self.navigationController viewControllers];
        if ([t count] >= 3) {
            UIViewController *vc = [t objectAtIndex:([t count]-3)];
            if ([vc isKindOfClass:[RCOrderManagerVC class]]) {
                [(RCOrderManagerVC *)vc refreshData];
            }
            
            [RCAppDelegate alertWithCustomizeString:@"提交成功"];
            [self performSelector:@selector(leftItemButtonClicked:) withObject:vc afterDelay:2.0f];

        }
       
    }else{
        [RCAppDelegate alertWithCustomizeString:dataModel.errorMsg];
    }
    
}

-(void)leftItemButtonClicked:(UIViewController *)vc{
    if (vc) {
        [self.navigationController popToViewController:vc animated:YES];
    }
    
}

#pragma -mark UITextFieldDelegate

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    
    return YES;
}


#pragma mark UITextFieldDelegate


-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if ([string isEqualToString:@"\n"]) {
        [textField resignFirstResponder];
        return NO;
    }
    return YES;
}

#pragma mark -
#pragma mark Responding to keyboard events
- (void)keyboardWillShow:(NSNotification *)notification {
    
    NSDictionary *userInfo = [notification userInfo];
    NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [value CGRectValue];
    
    CGFloat keyboardOriginY = UIScreenHeight-64-keyboardRect.size.height;
    
    CGFloat height = 261;
    
    CGFloat contentOffsetY = height - keyboardOriginY+5;
    
    if (contentOffsetY > 0) {
        [UIView animateWithDuration:0.3f animations:^{
            CGRect rect = self.viewContainer.frame;
            rect.origin.y = 0-contentOffsetY;
            self.viewContainer.frame = rect;
        }];
    }
    
    
}

- (void)keyboardWillHide:(NSNotification *)notification
{
    [UIView animateWithDuration:0.3f animations:^{
        CGRect rect = self.viewContainer.frame;
        rect.origin.y = 0;
        self.viewContainer.frame = rect;
    }];
}
@end
